package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.NewsComment;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.query.NewsCommentQueryObject;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.query.StrategyCommentQueryObject;
import cn.wolfcode.trip.base.service.INewsCommentService;
import cn.wolfcode.trip.base.service.INewsService;
import cn.wolfcode.trip.base.util.JsonResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Controller
@RequestMapping("/newscomment")
public class NewsCommentController {
    @Autowired
    private INewsCommentService newsCommentService;

    @Autowired
    private INewsService newsService;

    /**
     * 根据日报id查询评论
     * @param model
     * @param qo
     * @return
     */
    @GetMapping("/{newsId}/list")
    @ResponseBody
    public Object  list(Model model, @ModelAttribute("qo") NewsCommentQueryObject qo){
        qo.setOrderBy("sc.createTime desc");
        qo.setPageSize(0);
        PageInfo list = newsCommentService.list(qo);
        return list;
    }

    /**
     * 根据日报id查询评论的数量
     * @param newsId
     * @return
     */
    @GetMapping("/{newsId}/newsCount")
    @ResponseBody
    public int count(@PathVariable Long newsId){
        return newsCommentService.queryForCount(newsId);
    }

    /**
     * 新增日报评论
     *
     * @param newsId
     * @param commentContent
     * @return
     */
    @PostMapping
    @ResponseBody
    public JsonResult saveNewsComment(Long newsId,String commentContent){
        JsonResult jsonResult = new JsonResult();
        try {
            NewsComment newsComment = new NewsComment();
            newsComment.setCreateTime(new Date());
            newsComment.setContent(commentContent);
            User currentUser = UserContext.getCurrentUser();
            newsComment.setUser(currentUser);
            newsComment.setCommendTime(new Date());
            newsComment.setNews(newsService.getById(newsId));
            //设置状态普通
            newsComment.setState(NewsComment.STATE_NOMAL);
            newsCommentService.saveNewsComment(newsComment);
            return jsonResult;
        }catch (Exception e){
            e.printStackTrace();
            return jsonResult.mark("服务器繁忙!");
        }

    }
}
